import 'package:flutter/material.dart';
import 'dart:math';
import '../constants/app_colors.dart';

enum VoiceControlState {
  idle,      // 空闲状态
  starting,  // 正在启动
  recording, // 录音中
  processing // 处理中
}

class VoiceControlWidget extends StatefulWidget {
  final VoiceControlState state;
  final String recognizedText;
  final VoidCallback? onStartRecording;
  final VoidCallback? onStopRecording;
  final double? bottomPadding;

  const VoiceControlWidget({
    Key? key,
    required this.state,
    this.recognizedText = '',
    this.onStartRecording,
    this.onStopRecording,
    this.bottomPadding,
  }) : super(key: key);

  @override
  State<VoiceControlWidget> createState() => _VoiceControlWidgetState();
}

class _VoiceControlWidgetState extends State<VoiceControlWidget>
    with TickerProviderStateMixin {
  late AnimationController _pulseController;
  late AnimationController _breathingController;
  late AnimationController _expandController;
  late AnimationController _waveController;

  late Animation<double> _pulseAnimation;
  late Animation<double> _breathingAnimation;
  late Animation<double> _expandAnimation;
  late Animation<double> _waveAnimation;

  @override
  void initState() {
    super.initState();
    _initAnimations();
  }

  void _initAnimations() {
    // 脉冲动画
    _pulseController = AnimationController(
      duration: const Duration(milliseconds: 1200),
      vsync: this,
    );
    _pulseAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _pulseController, curve: Curves.easeInOut),
    );

    // 呼吸动画
    _breathingController = AnimationController(
      duration: const Duration(milliseconds: 2000),
      vsync: this,
    );
    _breathingAnimation = Tween<double>(begin: 0.98, end: 1.02).animate(
      CurvedAnimation(parent: _breathingController, curve: Curves.easeInOut),
    );

    // 展开动画
    _expandController = AnimationController(
      duration: const Duration(milliseconds: 400),
      vsync: this,
    );
    _expandAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _expandController, curve: Curves.easeOutBack),
    );

    // 声波动画
    _waveController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );
    _waveAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _waveController, curve: Curves.linear),
    );
  }

  @override
  void didUpdateWidget(VoiceControlWidget oldWidget) {
    super.didUpdateWidget(oldWidget);

    // 根据状态变化控制动画
    if (widget.state != oldWidget.state) {
      _handleStateChange(oldWidget.state, widget.state);
    }
  }

  void _handleStateChange(VoiceControlState oldState, VoiceControlState newState) {
    switch (newState) {
      case VoiceControlState.idle:
        _stopAllAnimations();
        _expandController.reverse();
        break;

      case VoiceControlState.starting:
        _pulseController.repeat(reverse: true);
        _expandController.forward();
        break;

      case VoiceControlState.recording:
        _pulseController.repeat(reverse: true);
        _breathingController.repeat(reverse: true);
        _waveController.repeat();
        _expandController.forward();
        break;

      case VoiceControlState.processing:
        _waveController.stop();
        break;
    }
  }

  void _stopAllAnimations() {
    _pulseController.stop();
    _breathingController.stop();
    _waveController.stop();
  }

  @override
  void dispose() {
    _pulseController.dispose();
    _breathingController.dispose();
    _expandController.dispose();
    _waveController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Positioned(
      left: 20,
      right: 20,
      bottom: widget.bottomPadding ?? 20,
      child: AnimatedBuilder(
        animation: Listenable.merge([
          _expandAnimation,
          _breathingAnimation,
        ]),
        builder: (context, child) {
          return Transform.scale(
            scale: widget.state == VoiceControlState.recording
                ? _breathingAnimation.value
                : 1.0,
            child: _buildControlWidget(),
          );
        },
      ),
    );
  }

  Widget _buildControlWidget() {
    final isActive = widget.state != VoiceControlState.idle;

    if (isActive) {
      return _buildActiveContainer();
    } else {
      return _buildIdleContainer();
    }
  }

  // 空闲状态容器
  Widget _buildIdleContainer() {
    return Container(
      height: 56, // 固定高度，避免布局问题
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(28),
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Colors.white.withValues(alpha: 0.0),
            Colors.white.withValues(alpha: 0.3),
            Colors.white.withValues(alpha: 0.7),
          ],
        ),
      ),
      child: Center(
        child: ElevatedButton.icon(
          onPressed: widget.onStartRecording,
          icon: const Icon(Icons.mic),
          label: const Text('开始同传'),
          style: ElevatedButton.styleFrom(
            backgroundColor: AppColors.primary,
            foregroundColor: Colors.white,
            padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(28),
            ),
            elevation: 12,
            shadowColor: AppColors.primary.withValues(alpha: 0.4),
          ),
        ),
      ),
    );
  }

  // 活跃状态容器
  Widget _buildActiveContainer() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white.withValues(alpha: 0.75),
        borderRadius: BorderRadius.circular(24),
        border: Border.all(
          color: AppColors.primary.withValues(alpha: 0.2),
          width: 1.5,
        ),
        boxShadow: [
          BoxShadow(
            color: AppColors.primary.withValues(alpha: 0.15),
            blurRadius: 20,
            offset: const Offset(0, 8),
          ),
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Colors.white.withValues(alpha: 0.8),
            Colors.white.withValues(alpha: 0.6),
          ],
        ),
      ),
      child: GestureDetector(
        onTap: widget.onStopRecording,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 录音状态指示器行
              Row(
                children: [
                  _buildRecordingIndicator(),
                  const SizedBox(width: 12),
                  _buildSoundWave(),
                  const SizedBox(width: 16),
                  Expanded(
                    child: _buildStatusText(),
                  ),
                  _buildStopButton(),
                ],
              ),

              // 识别文本区域（如果有文本）
              if (widget.recognizedText.isNotEmpty) ...[
                const SizedBox(height: 12),
                _buildRecognizedTextArea(),
              ],
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildRecordingIndicator() {
    return AnimatedBuilder(
      animation: _pulseAnimation,
      builder: (context, child) {
        return Stack(
          alignment: Alignment.center,
          children: [
            // 外圈脉冲
            Container(
              width: 24 + _pulseAnimation.value * 8,
              height: 24 + _pulseAnimation.value * 8,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(
                  color: AppColors.error.withValues(alpha: 0.4 * _pulseAnimation.value),
                  width: 2,
                ),
              ),
            ),
            // 内圈录音点
            Container(
              width: 12,
              height: 12,
              decoration: BoxDecoration(
                color: AppColors.error,
                shape: BoxShape.circle,
                boxShadow: [
                  BoxShadow(
                    color: AppColors.error.withValues(alpha: _pulseAnimation.value * 0.8),
                    blurRadius: _pulseAnimation.value * 8,
                    spreadRadius: _pulseAnimation.value * 2,
                  ),
                ],
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _buildSoundWave() {
    return AnimatedBuilder(
      animation: _waveAnimation,
      builder: (context, child) {
        return Row(
          mainAxisSize: MainAxisSize.min,
          children: List.generate(4, (index) {
            final delay = index * 0.2;
            final animationValue = (_waveAnimation.value + delay) % 1.0;
            final height = 4 + (sin(animationValue * 2 * pi) * 8).abs(); // 减小声波高度

            return Container(
              width: 3,
              height: height,
              margin: const EdgeInsets.symmetric(horizontal: 1),
              decoration: BoxDecoration(
                color: AppColors.primary.withValues(alpha: 0.7 + animationValue * 0.3),
                borderRadius: BorderRadius.circular(1.5),
              ),
            );
          }),
        );
      },
    );
  }

  Widget _buildStatusText() {
    String statusText;
    Color statusColor;

    switch (widget.state) {
      case VoiceControlState.starting:
        statusText = '正在启动...';
        statusColor = AppColors.primary.withValues(alpha: 0.8);
        break;
      case VoiceControlState.recording:
        statusText = '正在录音...';
        statusColor = AppColors.primary;
        break;
      case VoiceControlState.processing:
        statusText = '正在处理...';
        statusColor = AppColors.primary.withValues(alpha: 0.8);
        break;
      default:
        statusText = '';
        statusColor = Colors.black87;
    }

    return Text(
      statusText,
      style: TextStyle(
        fontSize: 14,
        color: statusColor,
        fontWeight: FontWeight.w600,
      ),
    );
  }

  Widget _buildStopButton() {
    return Container(
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: AppColors.error.withValues(alpha: 0.1),
        shape: BoxShape.circle,
      ),
      child: const Icon(
        Icons.stop,
        color: AppColors.error,
        size: 20,
      ),
    );
  }

  Widget _buildRecognizedTextArea() {
    return Container(
      width: double.infinity,
      constraints: const BoxConstraints(
        minHeight: 24,
        maxHeight: 48, // 减小最大高度，确保不溢出
      ),
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: Colors.white.withValues(alpha: 0.9),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: AppColors.primary.withValues(alpha: 0.1),
          width: 1,
        ),
      ),
      child: Center(
        child: AnimatedSwitcher(
          duration: const Duration(milliseconds: 200),
          child: Text(
            widget.recognizedText,
            key: ValueKey(widget.recognizedText),
            style: const TextStyle(
              fontSize: 13, // 减小字体
              color: Colors.black87,
              fontWeight: FontWeight.w500,
              height: 1.2, // 减小行高
            ),
            maxLines: 2, // 最多2行
            overflow: TextOverflow.ellipsis,
            textAlign: TextAlign.start,
          ),
        ),
      ),
    );
  }
}